package model

import (
	"context"
	"database/sql"
	"fmt"

	"github.com/Masterminds/squirrel"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

var _ UmsAdminRoleRelationModel = (*customUmsAdminRoleRelationModel)(nil)

type (
	// UmsAdminRoleRelationModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUmsAdminRoleRelationModel.
	UmsAdminRoleRelationModel interface {
		umsAdminRoleRelationModel
		Trans(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error
		RowBuilder() squirrel.SelectBuilder
		CountBuilder(field string) squirrel.SelectBuilder
		InsertById(ctx context.Context, data *UmsAdminRoleRelation) error
	}

	customUmsAdminRoleRelationModel struct {
		*defaultUmsAdminRoleRelationModel
	}
)

// NewUmsAdminRoleRelationModel returns a model for the database table.
func NewUmsAdminRoleRelationModel(conn sqlx.SqlConn, c cache.CacheConf) UmsAdminRoleRelationModel {
	return &customUmsAdminRoleRelationModel{
		defaultUmsAdminRoleRelationModel: newUmsAdminRoleRelationModel(conn, c),
	}
}
func (m *defaultUmsAdminRoleRelationModel) InsertById(ctx context.Context, data *UmsAdminRoleRelation) error {
	umsAdminRoleRelationIdKey := fmt.Sprintf("%s%v", cacheUmsAdminRoleRelationIdPrefix, data.Id)
	_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("insert into %s (%s) values (?,?)", m.table, "id,role_ids")
		return conn.ExecCtx(ctx, query, data.Id, data.RoleIds)
	}, umsAdminRoleRelationIdKey)

	return err
}

// export logic
func (m *defaultUmsAdminRoleRelationModel) Trans(ctx context.Context, fn func(ctx context.Context, session sqlx.Session) error) error {
	return m.TransactCtx(ctx, func(ctx context.Context, session sqlx.Session) error {
		return fn(ctx, session)
	})

}

//RowBuilder export logic
func (m *defaultUmsAdminRoleRelationModel) RowBuilder() squirrel.SelectBuilder {
	return squirrel.Select(umsAdminRoleRelationRows).From(m.table)
}

//CountBuilder export logic
func (m *defaultUmsAdminRoleRelationModel) CountBuilder(field string) squirrel.SelectBuilder {
	return squirrel.Select("COUNT(" + field + ")").From(m.table)
}

//SumBuilder export logic
func (m *defaultUmsAdminRoleRelationModel) SumBuilder(field string) squirrel.SelectBuilder {
	return squirrel.Select("IFNULL(SUM(" + field + "),0)").From(m.table)
}
